// 数据展示的js文件

// 请求随机推荐数据
$.ajax({
  type: 'get',
  url: 'posts/random',
  success: function (response) {
    const randomTpl = `
    {{each data}}
    <li>
      <a href="detail.html?id={{$value._id}}">
        <p class="title">{{$value.title}}</p>
        <p class="reading">阅读({{$value.meta.views}})</p>
        <div class="pic">
          <img src="{{$value.thumbnail}}" alt="">
        </div>
      </a>
    </li>
    {{/each}}
    `;
    const html = template.render(randomTpl, {data: response});
    $('#randomBox').html(html);
  }
})

// 请求最新评论数据
$.ajax({
  type: 'get',
  url: '/comments/lasted',
  success: function (response) {
    const commentsTpl = `
    {{each data}}
    <li>
      <a href="javascript:;">
        <div class="avatar">
          <img src="{{$value.author.avatar}}" alt="">
        </div>
        <div class="txt">
          <p>
            <span>{{$value.author.nickName}}</span>{{$value.createTime}}说:
          </p>
          <p>{{$value.content}}</p>
        </div>
      </a>
    </li>
    {{/each}}
    `;
    const html = template.render(commentsTpl, {data: response});
    $('#commentsBox').html(html);
  }
})

// 请求分类列表数据
$.ajax({
  type: 'get',
  url: '/categories',
  success: function (response) {
    const categoriesTpl = `
    {{each data}}
    <li><a href="list.html?categoryId={{$value._id}}"><i class="fa {{$value.className}}"></i>{{$value.title}}</a></li>
    {{/each}}
    `;
    const html = template.render(categoriesTpl, {data: response});
    $('#navBox').html(html);
    $('#topnav').html(html);
  }
})

// 从浏览器的地址栏获取参数
function getUrlParams(name) {
  const paramsAry = location.search.substr(1).split('&');
  for(let i = 0; i < paramsAry.length; i++) {
    const arr = paramsAry[i].split('=');
    if(arr[0] === name){
      return arr[1]
    }
  }
  return -1;
}

// 获取到搜索表单
$('.search form').on('submit', function () {
  const keys = $(this).find('.keys').val();
  // 跳转到搜索结果页面
  location.href = '/search.html?key='+keys;
  return false;
})